package com.peycard.servlet;

import java.io.IOException;
import java.text.ParseException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.peycard.common.PortalUserDTO;
import com.peycard.service.LoginService;

/**
 * Servlet implementation class RecuperaPassword
 */
public class RecuperaPassword extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RecuperaPassword() {
		super();
	}

	/**
	 * Método que envía el correo electrónico del usuario al servidor para
	 * obtener la pregunta de seguridad y así reestablecer su contraseña.
	 * Procesa la petición para el método HTTP <code>POST</code>
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void restorePassword(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		HttpSession session = request.getSession();
		LoginService service = new LoginService();
		String email = request.getParameter("email");

		try {
			PortalUserDTO usuario = service.securityQuestionRequest(email);

			if (usuario != null) {
				session.setAttribute("requestAudit", usuario.getAuditNumber());
				session.setAttribute("requestAnswer",
						usuario.getAnswerQuestion());
				session.setAttribute("requestQuestion",
						usuario.getSecurityQuestion());
				session.setAttribute("requestId", usuario.getIdPortalUser());

				RequestDispatcher requestDispatchet = request
						.getRequestDispatcher("/preguntaSecreta.jsp");
				requestDispatchet.forward(request, response);

			} else {
				String message = service.getMessage();
				request.setAttribute("message", message);
				RequestDispatcher requestDispatchet = request
						.getRequestDispatcher("/recupera.jsp");
				requestDispatchet.forward(request, response);
			}

		} catch (ParseException e) {
			String exceptionMsg = "Ocurrió un error al parsear la petición";
			request.setAttribute("message", exceptionMsg);
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// restorePassword(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		restorePassword(request, response);
	}
}
